#include "fridgecontroller.h"

FridgeController::FridgeController(QObject *parent)
    : QObject{parent}
{
    accessManager = new QNetworkAccessManager(this);
    connect(accessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");//构建json头
    //测试post
    //reply = accessManager->post(request, QByteArray("{\"password\": \"123456\", \"phone\": \"15683141454\"}"));
}

void FridgeController::FridgesynchronizeForm(QString token, QList<synFoodInfo> foodList, QList<synFridgeInfo> fridgeStorageList, QList<synRemindInfo> remindList, int fridgeId)
{
    request.setUrl(QUrl("http://81.70.102.35:8082/user/fridge/synchronize"));//设置url
    request.setRawHeader("Authorization",token.toLatin1());
    QJsonObject json;

    QJsonArray foodarray;
    QJsonObject foodobj;
    for(int i=0;i<foodList.size();i++)
    {
        foodobj.insert("alias",foodList[i].alias);
        foodobj.insert("createId",foodList[i].createId);
        foodobj.insert("createUser",foodList[i].createUser);
        foodobj.insert("gmtCreate",foodList[i].gmtCreate);
        foodobj.insert("gmtModified",foodList[i].gmtModified);
        foodobj.insert("info",foodList[i].info);
        foodobj.insert("name",foodList[i].name);
        foodobj.insert("pic",foodList[i].pic);
        foodobj.insert("shelfLife",foodList[i].shelfLife);
        foodobj.insert("type",foodList[i].type);
        foodobj.insert("unit",foodList[i].unit);
        foodobj.insert("version",foodList[i].version);
        foodarray.append(foodobj);
    }

    QJsonArray fridgeStoragearray;
    QJsonObject friageStorageobj;
    for(int i=0;i<fridgeStorageList.size();i++)
    {
        friageStorageobj.insert("amount",fridgeStorageList[i].amount);
        friageStorageobj.insert("foodId",fridgeStorageList[i].foodId);
        friageStorageobj.insert("fridgeId",fridgeStorageList[i].fridgeId);
        friageStorageobj.insert("gmtCreate",fridgeStorageList[i].gmtCreate);
        friageStorageobj.insert("gmtModified",fridgeStorageList[i].gmtModified);
        friageStorageobj.insert("userId",fridgeStorageList[i].userId);
        friageStorageobj.insert("version",fridgeStorageList[i].version);
        fridgeStoragearray.append(friageStorageobj);
    }

    QJsonArray rmindarray;
    QJsonObject rmindobj;
    for(int i=0;i<remindList.size();i++)
    {
        rmindobj.insert("amount",remindList[i].amount);
        rmindobj.insert("date",remindList[i].date);
        rmindobj.insert("foodId",remindList[i].foodId);
        rmindobj.insert("fridgeId",remindList[i].fridgeId);
        rmindobj.insert("gmtCreate",remindList[i].gmtCreate);
        rmindobj.insert("gmtModified",remindList[i].gmtModified);
        rmindobj.insert("id",remindList[i].id);
        rmindobj.insert("userId",remindList[i].userId);
        rmindobj.insert("version",remindList[i].version);
        rmindarray.append(rmindobj);
    }


    json.insert("fridgeId",fridgeId);
    json.insert("foodList",foodarray);
    json.insert("fridgeStorageList",fridgeStoragearray);
    json.insert("remindList",rmindarray);


    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    postData = jsonDocument.toJson(QJsonDocument::Compact);
    reply = accessManager->post(request,postData);
}
//测试成功
void FridgeController::FridgeBind(QString token,QString activeCode, QString id, QString password)
{
    request.setUrl(QUrl("http://81.70.102.35:8082/user/fridge/bind"));//设置url
    request.setRawHeader("Authorization",token.toLatin1());
    QJsonObject json;
    json.insert("activeCode",activeCode);
    json.insert("id",id);
    json.insert("password",password);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    postData = jsonDocument.toJson(QJsonDocument::Compact);
    reply = accessManager->post(request,postData);
}
//测试成功
void FridgeController::FridgeList(QString token)
{
    request.setUrl(QUrl("http://81.70.102.35:8082/user/fridge/list"));
    request.setRawHeader("Authorization",token.toLatin1());
    reply = accessManager->get(request);//发送GET请求
}
//太简单辣，懒的测试（出错就是insert错了）
void FridgeController::FridgeChangePass(QString token, int id, QString confirm, QString newPass, QString oldPass)
{
    request.setUrl(QUrl("http://81.70.102.35:8082/user/fridge/modifyPass"));//设置url
    request.setRawHeader("Authorization",token.toLatin1());
    QJsonObject json;
    json.insert("id",id);
    json.insert("confirm",confirm);
    json.insert("newPass",newPass);
    json.insert("oldPass",oldPass);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    postData = jsonDocument.toJson(QJsonDocument::Compact);
    reply = accessManager->post(request,postData);
}
//太简单辣，懒的测试（出错就是insert错了）
void FridgeController::FridgeUnbind(QString token, int version, QString gmtCreate, QString gmtModified, int valid, int isDeleted, int id, QString password, QString salt, QString name, QString createTime, QString activeTime, int guarantee, int userId, QString activeCode)
{
    request.setUrl(QUrl("http://81.70.102.35:8082/user/fridge/unBind"));//设置url
    request.setRawHeader("Authorization",token.toLatin1());
    QJsonObject json;
    json.insert("version",version);
    json.insert("gmtCreate",gmtCreate);
    json.insert("gmtModified",gmtModified);
    json.insert("valid",valid);
    json.insert("isDeleted",isDeleted);
    json.insert("id",id);
    json.insert("password",password);
    json.insert("salt",salt);
    json.insert("name",name);
    json.insert("createTime",createTime);
    json.insert("activeTime",activeTime);
    json.insert("guarantee",guarantee);
    json.insert("userId",userId);
    json.insert("activeCode",activeCode);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    postData = jsonDocument.toJson(QJsonDocument::Compact);
    reply = accessManager->post(request,postData);
}
//太简单辣，和上面一样，我直接cv啊
void FridgeController::FridgeUpdate(QString token, int version, QString gmtCreate, QString gmtModified, int valid, int isDeleted, int id, QString password, QString salt, QString name, QString createTime, QString activeTime, int guarantee, int userId, QString activeCode)
{
    request.setUrl(QUrl("http://81.70.102.35:8082/user/fridge/update"));//设置url
    request.setRawHeader("Authorization",token.toLatin1());
    QJsonObject json;
    json.insert("version",version);
    json.insert("gmtCreate",gmtCreate);
    json.insert("gmtModified",gmtModified);
    json.insert("valid",valid);
    json.insert("isDeleted",isDeleted);
    json.insert("id",id);
    json.insert("password",password);
    json.insert("salt",salt);
    json.insert("name",name);
    json.insert("createTime",createTime);
    json.insert("activeTime",activeTime);
    json.insert("guarantee",guarantee);
    json.insert("userId",userId);
    json.insert("activeCode",activeCode);
    QJsonDocument jsonDocument;
    jsonDocument.setObject(json);
    postData = jsonDocument.toJson(QJsonDocument::Compact);
    reply = accessManager->post(request,postData);
}

void FridgeController::finishedSlot(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        //qDebug() << "许凡楠大帅哥";
        //qDebug() << bytes;
        QJsonParseError jsonError;
        QJsonDocument doucment = QJsonDocument::fromJson(bytes, &jsonError);  // 转化为 JSON 文档
        QJsonObject object = doucment.object();
        if (object.contains("code"))
        {
            QJsonValue value = object.value("code");  // 获取指定 key 对应的 value
            this->m_message.code=value.toInt();
        }
        if(object.contains("message"))
        {
            QJsonValue value = object.value("message");
            this->m_message.message=value.toString();
            qDebug()<<this->m_message.message;
        }
        if(reply->url().toString()=="http://81.70.102.35:8082/user/fridge/bind")
        {
            //无返回
            emit bindSuccess();
        }
        if(reply->url().toString()=="http://81.70.102.35:8082/user/fridge/modifyPass")
        {
            //无返回
            emit changePassSuccess();
        }
        if(reply->url().toString()=="http://81.70.102.35:8082/user/fridge/unBind")
        {
            //无返回
            emit unBindSuccess();
        }
        if(reply->url().toString()=="http://81.70.102.35:8082/user/fridge/update")
        {
            //无返回
            emit updateSuccess();
        }
        if(reply->url().toString()=="http://81.70.102.35:8082/user/fridge/list")
        {
            this->fridgeList.clear();
            if(object.contains("data"))
            {
                QJsonValue value = object.value("data");
                if(value.isArray())
                {
                    QJsonArray array = value.toArray();
                    int nSize = array.size();
                    for(int i=0;i<nSize;i++)
                    {
                        QJsonValue value = array.at(i);
                        QJsonObject qobject = value.toObject();
                        friageInfo fridgeinfo;
                        if(qobject.contains("version"))
                        {
                            QJsonValue value = qobject.value("version");
                            fridgeinfo.version=value.toInt();
                        }
                        if(qobject.contains("valid"))
                        {
                            QJsonValue value = qobject.value("valid");
                            fridgeinfo.valid=value.toInt();
                        }
                        if(qobject.contains("isDeleted"))
                        {
                            QJsonValue value = qobject.value("isDeleted");
                            fridgeinfo.isDeleted=value.toInt();
                        }
                        if(qobject.contains("id"))
                        {
                            QJsonValue value = qobject.value("id");
                            fridgeinfo.id=value.toInt();
                        }
                        if(qobject.contains("guarantee"))
                        {
                            QJsonValue value = qobject.value("guarantee");
                            fridgeinfo.guarantee=value.toInt();
                        }
                        if(qobject.contains("userId"))
                        {
                            QJsonValue value = qobject.value("userId");
                            fridgeinfo.userId=value.toInt();
                        }
                        if(qobject.contains("gmtCreate"))
                        {
                            QJsonValue value = qobject.value("gmtCreate");
                            fridgeinfo.gmtCreate=value.toString();
                        }
                        if(qobject.contains("gmtModified"))
                        {
                            QJsonValue value = qobject.value("gmtModified");
                            fridgeinfo.gmtModified=value.toString();
                        }
                        if(qobject.contains("password"))
                        {
                            QJsonValue value = qobject.value("password");
                            fridgeinfo.password=value.toString();
                        }
                        if(qobject.contains("salt"))
                        {
                            QJsonValue value = qobject.value("salt");
                            fridgeinfo.salt=value.toString();
                        }
                        if(qobject.contains("name"))
                        {
                            QJsonValue value = qobject.value("name");
                            fridgeinfo.name=value.toString();
                        }
                        if(qobject.contains("createTime"))
                        {
                            QJsonValue value = qobject.value("createTime");
                            fridgeinfo.createTime=value.toString();
                        }
                        if(qobject.contains("activeTime"))
                        {
                            QJsonValue value = qobject.value("activeTime");
                            fridgeinfo.activeTime=value.toString();
                        }
                        if(qobject.contains("activeCode"))
                        {
                            QJsonValue value = qobject.value("activeCode");
                            fridgeinfo.activeCode=value.toString();
                        }
                        this->fridgeList.push_back(fridgeinfo);
                    }
                }
            }
            emit listSuccess();
        }
    }
    else
    {
        qDebug() << "finishedSlot errors here";
        qDebug( "found error .... code: %d\n", (int)reply->error());
        qDebug(qPrintable(reply->errorString()));
    }
    reply->deleteLater();
}
